// 处理书签栏数据逻辑// 目录互动功能逻辑
import { Menuss } from '@/typeing'
import { goFlat } from '@/utils/common'
import { getTreeAll } from '@/api'
import { dexieHistoryTag } from '@/hooks/dexie'
import { ref, reactive } from 'vue'
export default function(){
  const checkItem = reactive({
    key:'defaultKey', // 默认选中常用书签栏项
    id:'default'
  })
  const treeData = ref([] as Array<any>)
  const itemsObj = ref({} as {[x:string]: any})
  // const defaultTagMap:{[x:string]:any} = {}

  async function init(){
    const dTag = new dexieHistoryTag()
    let historyTag = await dTag.selectAll()
    
    historyTag = historyTag.sort((a,b) => (b.history! - a.history!))
    if(historyTag.length > 28) historyTag.splice(28)
    itemsObj.value.default = historyTag
    // 初始化书签数据
    if(chrome.bookmarks){
      chrome.bookmarks.getTree(function(bookmarkArray: any){
          const addKeyList = formatKey(bookmarkArray[0].children, '') // 给文件夹动态添加索引key
          const floderList = formatFloder(addKeyList) // 筛选类型为文件夹的数据
          treeData.value.push(...floderList) // 原树形结构，供生成菜单使用
          itemsObj.value = Object.assign(itemsObj.value, goFlat(addKeyList)) // 扁平化结构，供右侧展示书签列表用
      })
    }else{
      getTreeAll().then((res: any) => {
        const addKeyList = formatKey(res[0].children, '') // 给文件夹动态添加索引key
        const floderList = formatFloder(addKeyList) // 筛选类型为文件夹的数据
        treeData.value.push(...floderList)
        itemsObj.value = Object.assign(itemsObj.value, goFlat(addKeyList))
      })
    }
  }
  
  return {
    init,
    checkItem,
    treeData,
    itemsObj
  }
}



  // 遍历树结构，1.给类型为“目录”的添加key; 2.添加history 历史点击数
  function formatKey(par:Array<Menuss>, parentKey: string): Array<Menuss> {
    if(!par.length) return []
    const newAr: Array<Menuss> = []
    par.forEach((val,index)=>{
      const obj = {
        ...val
      }
      if(val.children){
        obj.key = parentKey ? `${parentKey}-${index}` : index+''
      }
      if(val.children && val.children.length){
        obj.children = formatKey(val.children, obj.key)
      }
      newAr.push(obj)
    })
    return newAr
  }

  // 只保留类型是文件夹的数据
  function formatFloder(par:Array<Menuss>): Array<Menuss> {
    if(!par.length) return []
    const newAr: Array<Menuss> = []
    par.forEach((val)=>{
      const obj = {
        ...val
      }
      if(val.children && val.children.length){
        obj.children = formatFloder(val.children)
      }
      if(!val.url){
        newAr.push(obj)
      }
    })
    return newAr
  }